package top.ieei.demo.dhcp;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

public final class DhcpUtil
{

    /**
     * 构造函数<br>
     */
    private DhcpUtil()
    {

    }

    public static final InetAddress int2InetAddress(int val)
    {
        byte[] value = {(byte) ((val & 0xFF000000) >>> 24), (byte) ((val & 0xFF0000) >>> 16),
                (byte) ((val & 0xFF00) >>> 8), (byte) (val & 0xFF)};
        try
        {
            return InetAddress.getByAddress(value);
        }
        catch (UnknownHostException e)
        {
        }
        return null;
    }

    public static final InetAddress long2InetAddress(long val)
    {
        if ((val >= 0L) && (val > 4294967295L))
            ;
        return int2InetAddress((int) val);
    }

    public static final int inetAddress2Int(InetAddress addr)
    {
        if (!(addr instanceof Inet4Address))
        {
            throw new IllegalArgumentException("Only IPv4 supported");
        }

        byte[] addrBytes = addr.getAddress();
        return (addrBytes[0] & 0xFF) << 24 | (addrBytes[1] & 0xFF) << 16 | (addrBytes[2] & 0xFF) << 8 | addrBytes[3]
                & 0xFF;
    }

    public static final long inetAddress2Long(InetAddress addr)
    {
        return inetAddress2Int(addr) & 0xFFFFFFFF;
    }
}